package org.dawnmew.jpurewave;

/**
 * Plays back a raw PCM sound file (in a '.au' container file) on a private
 * output line.
 *
 * @author dawnmew
 * @since 1.0
 *
 * Licensed under the MIT License.
 *
 * Copyright (c) 2012 dawnmew
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
import java.io.BufferedInputStream;
import java.io.IOException;
import javax.sound.sampled.*;
import org.dawnmew.jvirtualstream.VirtualFileSystem;

public class SoundRawInstance extends Thread
{

    private AudioInputStream inputStream = null;
    private String filepath;
    private SourceDataLine outputLine = null;
    private float volume;
    private int controlMode;
    private float minVolume;
    private SoundSystem parent;

    public SoundRawInstance(String filepath, float volume, int controlMode, float minVolume, SoundSystem parent)
    {
        this.parent = parent;
        this.filepath = filepath + ".au";
        this.volume = volume;
        this.controlMode = controlMode;
        this.minVolume = minVolume;
    }

    @Override
    public void run()
    {
        try
        {
            inputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(VirtualFileSystem.getInstance().getInputStream(filepath)));
        } catch (Exception ex)
        {
            System.err.println("Couldn't create SFX stream for: " + filepath);
            return;
        }

        if (inputStream == null)
        {
            return;
        }

        AudioFormat audioFormat = inputStream.getFormat();
        DataLine.Info datalineInfo = new DataLine.Info(SourceDataLine.class,
                audioFormat, AudioSystem.NOT_SPECIFIED);

        if (!AudioSystem.isLineSupported(datalineInfo))
        {
            return;
        }
        try
        {
            if (outputLine == null)
            {
                outputLine = (SourceDataLine) AudioSystem.getLine(datalineInfo);
                outputLine.open(audioFormat);
                outputLine.start();
            }
        } catch (LineUnavailableException exception)
        {
            System.out.println("The audio output line could not be opened due "
                    + "to resource restrictions.");
            System.err.println(exception);
            return;
        } catch (IllegalStateException exception)
        {
            System.out.println("The audio output line is already open.");
            System.err.println(exception);
            return;
        } catch (SecurityException exception)
        {
            System.out.println("The audio output line could not be opened due "
                    + "to security restrictions.");
            System.err.println(exception);
            return;
        }

        if (controlMode == 2)
        {
            ((FloatControl) outputLine.getControl(SoundSystem.volumeControlType)).setValue(volume);
        } else if (controlMode == 1)
        {
            ((FloatControl) outputLine.getControl(SoundSystem.gainControlType)).setValue(minVolume - (minVolume * volume));
        }

        try
        {
            byte[] buffer = new byte[4096];
            int x;
            while (true)
            {
                x = inputStream.read(buffer);
                if (x < 0)
                {
                    break;
                }
                outputLine.write(buffer, 0, x);
            }
        } catch (IOException ex)
        {
        }

        outputLine.drain();
        outputLine.close();
    }
}
